/*
 * Package: org.grassfield.common.dao
 * FileName: BaseDAO.java
 *  
 * Created by pandian on Jan 28, 2011
 */
package dao;

import java.util.List;

import javax.sql.DataSource;

import org.apache.log4j.Logger;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * The Class BaseDAO.
 */
public class BaseDAO extends HibernateDaoSupport implements IBaseDAO {
	protected Logger logger = Logger.getLogger(BaseDAO.class);
	protected DataSource dataSource;

	/**
	 * Sets the data source.
	 * 
	 * @param dataSource
	 *            the new data source
	 */
	public void setDataSource(DataSource dataSource) {
		this.dataSource = dataSource;
	}

	/* (non-Javadoc)
	 * @see org.grassfield.common.dao.IBaseDAO#save(java.lang.Object)
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED, readOnly=false)
	public Object save(Object entity){
		this.logger.info("Saving object:"+entity);
		HibernateTemplate hibernateTemplate = super.getHibernateTemplate();
		hibernateTemplate.saveOrUpdate(entity);
		hibernateTemplate.flush();
		hibernateTemplate.refresh(entity);
		hibernateTemplate.evict(entity);
		this.logger.info("Object save successful:"+entity);
		return entity;
	}
	
	/* (non-Javadoc)
	 * @see org.grassfield.common.dao.IBaseDAO#update(java.lang.Object)
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED, readOnly=false)
	public void update(Object entity){
		this.logger.info("update object:"+entity);
//		super.getHibernateTemplate().saveOrUpdate(entity);
		super.getHibernateTemplate().update(entity);
		super.getHibernateTemplate().flush();
		super.getHibernateTemplate().refresh(entity);
		this.logger.info("Object update successful:"+entity);
	}

	/* (non-Javadoc)
	 * @see org.grassfield.common.dao.IBaseDAO#list(java.lang.String)
	 */
	@Override
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public List list(String qry) {
		logger.debug("qry1:"+qry);
		List<Object> list = (List<Object>) super.getHibernateTemplate().find(qry);
		this.logger.debug("list1:"+list);
		return list;
	}
	
	/* (non-Javadoc)
	 * @see org.grassfield.common.dao.IBaseDAO#list(java.lang.String, java.lang.Object[])
	 */
	@Override
	@SuppressWarnings("unchecked")
	public List<Object> list(String qry, Object[] object) {
		logger.debug("qry2:"+qry);
		List<Object> list = (List<Object>) super.getHibernateTemplate().find(qry, object);
		logger.debug("list2:"+list);
		return list;
	}
}
